<template>
  <el-row>
    <el-col :span="24" style="margin-top:10px;">
      <slot name="search">
        <el-card class="box-card" v-if="seachFrom && seachFrom.length">
          <div slot="header" class="clearfix">
            <span>搜索</span>
          </div>
          <div>
            <xdh-form
              :model="seachFromData"
              :fields="seachFrom"
              footerAlign="inline"
              submitText="搜索"
              resetText="重置刷新"
              footerSize="medium"
              @submit="submitSearchForm"
              @reset="resetRefresh"
              :edits="true"
            >
              <template slot="submitIcon">
                <i class="el-icon-zoom-out"></i>
              </template>
              <template slot="resetIcon">
                <i class="el-icon-refresh"></i>
              </template>
            </xdh-form>
          </div>
        </el-card>
      </slot>
    </el-col>
    <el-col :span="24" style="margin-top:10px;">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-row>
            <el-col :span="24" v-if="note">
              <div style="padding-bottom:20px;padding-top:20px;color:red;" v-html="note">
                温馨提示：门店账号登录地址：
                <a href="http://localhost:9528/" target="_blank">http://localhost:9528/</a>
              </div>
            </el-col>
            <el-col :span="12">
              <slot name="leftButton">
                <template v-if="leftButton && leftButton.length">
                  <template v-for="(item,inx)  in  getButton(leftButton)">
                    <XdhTableItem
                      v-if="item['is-show']"
                      v-bind="item"
                      :key="inx"
                      :indexs="inx"
                      :txtValue="checkBoxData"
                      @buttonClick="function(obj){return buttonClick(obj,checkBoxData)}"
                    />
                  </template>
                </template>
              </slot>
            </el-col>
            <el-col :span="12" style="text-align: right;float: right;">
              <slot name="rightButton">
                <template v-if="rightButton && rightButton.length">
                  <el-button type="success" size="mini" icon="el-icon-refresh" @click="resetRefresh">刷新</el-button>
                  <el-button-group>
                    <template v-for="(item,inx)  in  getButton(rightButton)">
                      <span :key="inx">
                        <el-button
                          v-if="item.prop == 'import' && item['is-show']"
                          v-bind="item.props"
                          v-on="$listeners"
                          @click="checkImportButton(item)"
                        >{{item.props.value}}</el-button>

                        <!-- 导出 -->
                        <el-dropdown
                          v-else-if="item.prop == 'export' && item['is-show']"
                          v-bind="item.props"
                          split-button
                          trigger="click"
                          @command="function(command){return checkExportButton(command,item);}"
                        >
                          <i v-if="item.props.icon" :class="item.props.icon"></i>
                          {{item.props.value}}
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="check">导出当前选择</el-dropdown-item>
                            <el-dropdown-item command="search">导出搜索内容</el-dropdown-item>
                            <el-dropdown-item command="all">导出全部内容</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>

                        <!-- 打印 -->
                        <el-button
                          v-else-if="item.prop == 'printing' && item['is-show']"
                          v-bind="item.props"
                          v-on="$listeners"
                          @click="clickPrinting(item)"
                        >{{item.props.value}}</el-button>

                        <!-- 数据显示 -->
                        <el-dropdown
                          v-else-if="item.prop == 'field'"
                          v-bind="item.props"
                          split-button
                          trigger="click"
                          :hide-on-click="false"
                          @command="checkFielButton"
                        >
                          <i v-if="item.props.icon" :class="item.props.icon"></i>
                          <el-dropdown-menu slot="dropdown">
                            <template v-for="(item,inxd) in rulesUrl">
                              <el-dropdown-item :key="inxd" :command="inxd">
                                <i
                                  v-if="item['is-show']"
                                  class="el-icon-success"
                                  style="color:#409eff"
                                ></i>
                                <i v-else class="el-icon-remove"></i>
                                {{item.label}}
                              </el-dropdown-item>
                            </template>
                          </el-dropdown-menu>
                        </el-dropdown>
                      </span>
                    </template>
                  </el-button-group>
                </template>
              </slot>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-table
            ref="table"
            :data="tableData"
            v-on="$listeners"
            v-bind="tableOptions"
            @selection-change="handleSelectionChange"
            id="el-table"
          >
            <el-table-column type="selection" v-if="rulesUrl && rulesUrl.length"></el-table-column>
            <template v-for="(item,inxd) in rulesUrl">
              <el-table-column
                v-if="item['is-show'] || tableIsShow"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
                :width="item.width"
                :align="item['align']||'left'"
                :header-align="item['header-align']||''"
              >
                <template slot="header">
                  <slot name="edithead" v-bind="{item:item,index:inxd}"></slot>
                </template>
                <template slot-scope="scope">
                  <XdhTableItem
                    v-bind="item"
                    :value="scope.row[item.prop]"
                    :txtValue="scope.row"
                    :indexs="inxd"
                    @buttonClick="function(obj){return buttonClick(obj,scope.row)}"
                    @sortChange="function(obj){return sortChange(obj,scope.row,item)}"
                  />
                </template>
              </el-table-column>
            </template>
          </el-table>
          <slot name="tuozhuai"></slot>
        </div>

        <div solt="footer" style="margin-top:20px" v-if="listQuery.page">
          <slot name="footerPage">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="listQuery.page"
              :page-size="listQuery.total"
              :page-sizes="listQuery.pageSizes"
              layout="total, sizes, prev, pager, next, jumper"
              :total="parseInt(listQuery.totalCount)"
            ></el-pagination>
          </slot>
        </div>

        <el-dialog
          title="导入数据转换"
          :visible.sync="importHtmlIsShow"
          width="60%"
          :before-close="function(){return importHtmlIsShow = false}"
        >
          <import-html :key="getkey()" :data="rulesUrl" v-bind="importAttrs" @click="importClick"></import-html>
        </el-dialog>

        <el-dialog
          :title="alertTitle"
          :visible.sync="alertHtmlIsShow"
          :width="alertWidth"
          :height="alertheight"
          :before-close="function(){return alertHtmlIsShow = false}"
          append-to-body
        >
          <alert-html
            :key="getkey()"
            :data="alertData"
            v-bind="alertAttrs"
            @submit="alertSubmit"
            @reset="alertReset"
          ></alert-html>
        </el-dialog>
      </el-card>
    </el-col>
  </el-row>
</template>
<script>
import ElTable from "element-ui/lib/table";
import { mapState, mapGetters } from "vuex";
import XdhTableItem from "./xdh-table-item";

import analysisRouterParam from "@/utils/analysis-router-param.js";
import { commonGetInfo } from "@/api/common";
// import modules from "@/widgets/helper/setting";


import { getInfo } from "@/api/tpl";
import { validateIsNumber } from "@/utils/validate";

import {validateRule,validateButtonRule,checkExport} from '@/utils/util';

//   import {debounce} from '@/utils/util'
//   import {insertAfter} from '@/utils/dom'
//   import bus from '@/utils/bus'

/**
 * XdhTable 表格组件
 * @module widgets/xdh-table
 */
export default {
  name: "XdhTable",
  /**
   * 属性参数，完全继承 el-table参数，并有以下扩展参数
   * @property {Array} [data = []] 表格行数据
   * @property {Array} [columns = []]  表格列定义，对象属性参数完全继承 el-table-column
   * @property {Object | Boolean} [columnSortable = false] 是否启用列拖拽排序, 可以配置Sortable个性化参数
   * @property {Object | Boolean} [rowSortable = false] 是否启用行拖拽排序, 可以配置Sortable个性化参数
   * @property {Number} [distanceToButton = 50] 滚动到距离底部多少距离触发 on-reach-bottom 事件， table需要设置高度才有效
   * @property {Function} [openFilter] 处理打开filter事件，必须返回 Promise实例，如需要显示下拉字典时可以用到
   */
  components: {
    XdhTableItem,
    ImportHtml:()=>import('@/widgets/xdh-table/src/import.vue'),
    XdhForm:()=>import('@/widgets/xdh-form'),
    AlertHtml:()=>import('@/views/base/alert/index.vue'),
  },
  props: {
    ...ElTable.props,
    columns: {
      type: Array,
      default() {
        return [];
      },
    },
    columnSortable: {
      type: [Object, Boolean],
      default: false,
    },
    rowSortable: {
      type: [Object, Boolean],
      default: false,
    },
    distanceToButton: {
      type: Number,
      default: 50,
    },
    note: {
      type: String,
      default: "",
    },
    leftButton: {
      type: Array,
      default: () => [],
    },
    rightButton: {
      type: Array,
      default: () => [],
    },
    seachFrom: {
      type: Array,
      default: () => [],
    },
    tableIsShow: {
      type: Boolean,
      default: true,
    },
    listQueryData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    title:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      alertTitle: "",
      alertHtmlIsShow: false,
      alertWidth: "60%",
      alertheight: "100%",
      alertAttrs: {},
      alertData: {},
      checkBoxData: [],
      seachFromData: {},
      importHtmlIsShow: false,
      importAttrs: {},
      // 表格列定义数组
      tableColumns: [],

      // 表格行数据
      // 表格行数据
      tableData: this.data,

      // 列拖拽Sortable实例
      columnSortableInstance: null,

      // 行拖拽Sortable实例
      rowSortableInstance: null,

      // 上次滚动的位置
      lastScrollTop: 0,

      // 筛选框的实例
      filterVM: {},

      listQuery: this.listQueryData,
    };
  },
  computed: {
    ...mapState({
      form: (state) => state.formModel,
      fields: (state) => state.fields,
      sortable_item: (state) => state.fields,
      tableField: (state) => state.tableField,
      // sortable_items: state => state.tableField,
      editField: (state) => state.editField,
    }),
    ...mapGetters(["model", "tableModel", "routerRules"]),
    parent() {
      return getParent.call(this);
    },
    extendAttrs() {
      return getExtendAttrs.call(this);
    },
    labelWidth() {
      return this.extendAttrs.labelWidth || "";
    },
    fieldValue: {
      get() {
        const model = this.parent.currentModel;
        if (model) {
          return getPropByPath(model, this.prop.toString(), true).v;
        }
        return null;
      },
      set(val) {
        const model = this.parent.currentModel;
        const prop = getPropByPath(model, this.prop.toString());
        this.$set(prop.o, prop.k, val);
      },
    },
    // el-table 参数
    tableOptions() {
      let options = { ...this.$props };
      delete options.columns;
      delete options.data;
      delete options.columnSortable;
      delete options.rowSortable;
      delete options.distanceToButton;
      return options;
    },
    rulesUrl() {
      if (this.tableIsShow) {
        return this.columns;
      }

      this.tableColumns = validateRule(this.columns,this.routerRules);
      return this.tableColumns;
    },
  },
  watch: {
    data(val) {
      // console.log(val, '================================================================')
      this.tableData = val;
    },
    columns(val) {
      this.tableColumns = val;
      const data = this.tableData;
      this.tableData = [];
      this.$nextTick(() => {
        this.tableData = data;
      });
    }
  },
  created() {},
  methods: {
    getButton(val) {
      if (this.tableIsShow) {
        return val;
      }
      
      return validateButtonRule(val,this.routerRules);
    },
    //分页total
    handleSizeChange(val) {
      this.$emit("handleSizeChange", val);
    },
    //分页page
    handleCurrentChange: function (val) {
      this.$emit("handleCurrentChange", val);
    },
    //弹出层模板初始化
    async alertInit({ path, query, width, height, tips }) {
      let tplId = path.replace("/", "");
      if (validateIsNumber(tplId) === false) {
        return false;
      }

      var d = {
        id: tplId,
      };
      const res = await getInfo(d);
      if (res && res.code === 200) {
        this.alertTitle = tips;
        if(width) {
          this.alertWidth = width;
        }
        this.alertheight = height;
        this.alertAttrs = res.data.info;
        this.alertHtmlIsShow = true;
        this.alertData = query;
      }
    },
    //弹出层提交
    alertSubmit() {
      this.alertHtmlIsShow = false;
      this.$emit("refreshInit", this.listQuery);
    },
    //关闭弹出层
    alertReset() {
      this.alertHtmlIsShow = false;
    },
    //搜索
    submitSearchForm(formDatas) {
      this.seachFromData = formDatas;
   
      this.$emit("submitSearchForm", formDatas);
    },
    //重置刷新
    resetRefresh() {
      this.listQuery.page = 1;
      this.listQuery.search = {};
      this.$emit("refreshInit", this.listQuery);
    },
    //导入按钮
    checkImportButton(item) {
      this.importHtmlIsShow = true;
      this.importAttrs = item.props;
    },
    async importClick(data, item) {
      if (data.length == 0) {
        this.$message({
          message: "文件数据解析错误或者为空文件",
          type: "error",
        });
        return false;
      }
     
      const res = await commonGetInfo(item.url, {data:data});
      if (res && res.code === 200) {
          this.$message({
            message: res.msg,
            type: "success",
          });
          this.importHtmlIsShow = false;
          this.$emit("refreshInit", this.listQuery);
          return false;
      }
      this.importHtmlIsShow = false;
      return false;
    },
    //导出按钮
    async checkExportButton(command, item) {
      // this.$emit('checkExportButton',{command:command,item:item,columns:this.columns})
      var route = {};
      
      switch(command) {
          case 'check':
                if (JSON.stringify(this.checkBoxData) == "{}" || JSON.stringify(this.checkBoxData) == "[]") {
                  this.$message({
                    message: "请先选择需要操作的数据",
                    type: "error",
                  });
                  return false;
                }
                route = analysisRouterParam.init(item.props.url, this.checkBoxData);
                var query = route.query;
                route.query = {};
                route.query.check = query;
                break;
          case 'search':
                route = analysisRouterParam.init(item.props.url, {});
                route.query.search = this.listQuery.search;
                break;    
          default:
                route = analysisRouterParam.init(item.props.url, {});
                break;        
      }
      route.query.command = command;
      if(!route.path) {
        return false;
      }
      const res = await commonGetInfo(route.path, route.query);
      if (res && res.code === 200) {
          checkExport(res.data.list,this.columns,this.title);
      }
      
    },
    //列表数据字段是否显示按钮操作
    checkFielButton(command) {
      this.tableColumns[command]["is-show"] = !this.tableColumns[command]["is-show"];
      this.$forceUpdate();
    },
    //打印
    clickPrinting() {
      var printWin = window.open("about:blank", "_blank"),
        style = [
          "<style>",
          "body{font-size: 12px; color: #666;}",
          "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
          "th,td{line-height: 20px; padding: 9px 15px; border: 1px solid #ccc; text-align: left; font-size: 12px; color: #666;}",
          "a{color: #666; text-decoration:none;}",
          "*.layui-hide{display: none}",
          "</style>",
        ].join(""),
        html = document.getElementById("el-table").innerHTML;
      printWin.document.write(style + html);
      printWin.document.close();
      printWin.print();
      printWin.close();
    },
    sortChange(obj, row, item) {
      var routerUrl = analysisRouterParam.init(item.props.url, row);
      if (!routerUrl.path) {
        return false;
      }
      routerUrl.query.value = obj.value;
      this.confirmAjax(routerUrl);
    },
    buttonClick: function (obj, list) {
      if (!obj.url && obj.changes !== 'click') {
        return false;
      }
      var routerUrl = analysisRouterParam.init(obj.url, list);
          
      switch (obj.changes) {
        case "click":
          this.$emit('bottonClick',list);
          break;
        case "jump":
          var that = this;
          routerUrl.query.page = this.listQuery.page;
          routerUrl.query.total = this.listQuery.total;
          // routerUrl.query.search = this.listQuery.search;
          // console.log(obj.routeName,'+++++++')
          // return false;
          if(obj.routeName) {
            console.log({name:obj.routeName,query:routerUrl.query},'+++++++')
            that.$router.push({name:obj.routeName,query:routerUrl.query});
          }else{
            that.$router.push(routerUrl);
          }
          
          // 
          // this.$router.push({path: "/admin/menu/add", query: {}});
          break;
        case "blank":
          const urlObj = this.$router.resolve(routerUrl);
          window.open(urlObj.href, "_blank");
          break;
        case "alert":
          this.alertInit(Object.assign(routerUrl, obj));
          break;
        case "ajax":
          if (JSON.stringify(list) == "{}" || JSON.stringify(list) == "[]") {
            this.$message({
              message: "请先选择需要操作的数据",
              type: "error",
            });
            return false;
          }
          routerUrl.path = obj.powerUrl;
          if (obj.tips) {
            this.$confirm(obj.tips, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.confirmAjax(routerUrl);
              })
              .catch(() => {
                console.log("取消");
              });
          } else {
            this.confirmAjax(routerUrl);
          }
          break;
      }
    },
    async confirmAjax(route) {
      const res = await commonGetInfo(route.path, route.query);
      if (res && res.code === 200) {
        this.$message({
          type: "success",
          message: res.msg,
        });
        this.$emit("refreshInit", this.listQuery);
      }
    },
    //全选
    handleSelectionChange: function (val) {
      this.checkBoxData = val;
    },
    handleEditItem(item, index) {
      item.index = index;
      let info = Object.assign({}, item);
      // this.$store.dispatch('user/setNodeinfo', info);
      this.$store.commit("setEditTableField", info);
    },
    removeItem(item) {
      const isDepend = !!this.tableField.find((n) => n.depend === item.prop);
      if (isDepend) {
        this.$message.warning("该字段被其他字段依赖，不能删除");
        return;
      }
      this.$store.commit("setEditTableField", null);
      this.$store.commit("removeTableField", item);
    },
    getkey() {
      return Math.random();
    },
  },
};
</script>
